/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-03-27 11:56:42
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2025-05-28 10:08:45
 * @FilePath: /vue3-admin/src/views/system/MenusManage/components/EditView/useForm.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { ref, type Ref, watch } from 'vue';
import { useMenu, MenuParam } from '@/service/biz/useMenu';
import { useRules } from '@/service/useRules';
import type { FormInstance } from 'element-plus';

export const useForm = (
    formRef: Ref<FormInstance | undefined>,
    idRef: Ref<number | undefined> | undefined,
    addIdRef: Ref<number | undefined> | undefined,
    modelValueRef: Ref<boolean>,
    afterSubmit: () => void
) => {
    const dialogTitle = ref('新增');

    const { updateMenu, getDetail, detailLoading, detail, updateLoading } =
        useMenu();

    const formModel = ref(new MenuParam());

    const { requiredRule } = useRules();

    const rules = {
        name: [...requiredRule],
        parentId: [...requiredRule]
    };

    const handleSubmit = () => {
        formRef.value?.validate(async (isValid) => {
            if (isValid) {
                const model = formModel.value;
                model.parentId =
                    model.parentId === -1 ? undefined : model.parentId;
                await updateMenu(model);
                afterSubmit();
            }
        });
    };

    const handleEdit = async (id?: number, aid?: number) => {
        formModel.value = new MenuParam();
        formModel.value.type = 1;
        formModel.value.parentId = -1; // -1作为空标识，表示父节点是根节点，传过去时要置为undefined
        if (id) {
            dialogTitle.value = '修改';
            await getDetail(id);
            formModel.value.id = idRef && idRef.value;
            formModel.value.name = detail.value?.name ?? '';
            formModel.value.parentId = detail.value?.parentId ?? -1;
            formModel.value.path = detail.value?.path ?? '';
            formModel.value.icon = detail.value?.icon ?? '';
            formModel.value.sortWeight = detail.value?.sortWeight ?? 1;
        } else if (aid) {
            dialogTitle.value = '添加子项';
            formModel.value.parentId = aid;
        } else {
            dialogTitle.value = '添加';
        }
    };

    watch(
        () => modelValueRef.value,
        (newVal) => {
            if (newVal) {
                formRef.value?.clearValidate();
                handleEdit(idRef && idRef.value, addIdRef && addIdRef.value);
            }
        },
        {
            immediate: true
        }
    );

    return {
        dialogTitle,
        formModel,
        detailLoading,
        updateLoading,
        handleSubmit,
        handleEdit,
        rules
    };
};
